<?php

namespace App\Admin\Controllers;

use App\Admin\Actions\Grid\Customer\Allocate;
use App\Admin\Actions\Grid\Customer\AutoAllocate;
use App\Admin\Actions\Grid\Customer\Balance;
use App\Admin\Actions\Grid\Customer\Delete;
use App\Admin\Actions\Grid\Customer\ReceptionAllocate;
use App\Admin\Actions\Grid\Customer\ReceptionAutoAllocate;
use App\Admin\Actions\Grid\Customer\Register;
use App\Admin\Actions\Grid\Customer\Remark;
use App\Admin\Actions\Grid\Customer\ReturnPerformance;
use App\Admin\Actions\Grid\Customer\SalePerformance;
use App\Admin\Repositories\Customer;
use App\Enums\CustomerLabel;
use App\Enums\DataPermission;
use App\Enums\OptionType;
use App\Enums\ReceptionType;
use App\Enums\SalePerformanceType;
use App\Services\OptionService;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Show;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;

class CustomerController extends AdminController
{

    public int $type;
    public bool $is_sale;
    public bool $is_return_visit;
    public bool $is_reception;


    public function __construct(Request $request)
    {
        $this->type = (int)$request->get('type', ReceptionType::SALE);
        $this->is_sale = $this->type === ReceptionType::SALE;
        $this->is_return_visit = $this->type === ReceptionType::RETURN_VISIT;
        $this->is_reception = $this->type === ReceptionType::RECEPTION;
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid(): Grid
    {
        return Grid::make(new Customer(), function (Grid $grid) {

            //新增按钮追加参数
            $grid->model()->setConstraints([
                'type' => $this->type,
            ]);
            $data_permission_is_all = $this->getAdminDataPermission() == DataPermission::ALL;

            $grid->model()
                ->when($this->is_reception, function (Builder $builder) {
                    $builder->with(['receptionUser', 'saleUser', 'source']);
                })
                ->when($this->is_sale, function (Builder $builder) {
                    $builder->with(['saleUser', 'returnUser', 'source', 'salePerformanceFirst', 'salePerformance']);
                })
                ->when($this->is_return_visit, function (Builder $builder) {
                    $builder->with(['saleUser', 'returnUser']);
                })
                ->when($data_permission_is_all, function (Builder $builder) {
                    //全部数据
                    if ($this->is_reception) {
                        //接待部
                        $builder->where('reception_user_id', '>', 0);
                    }
                    if ($this->is_sale) {
                        //销售部
                        $builder->where('sale_user_id', '>', 0);
                    }
                    if ($this->is_return_visit) {
                        //复诊部
                        $builder->where('return_user_id', '>', 0);
                    }
                }, function (Builder $builder) {
                    //自己相关
                    if ($this->is_reception) {
                        //销售部
                        $builder->where('reception_user_id', self::getUserId());
                    }
                    if ($this->is_sale) {
                        //销售部
                        $builder->where('sale_user_id', self::getUserId());
                    }
                    if ($this->is_return_visit) {
                        //复诊部
                        $builder->where('return_user_id', '>', 0)->where('return_user_id', self::getUserId());
                    }
                })
                ->orderByDesc('id');

            if ($this->is_reception) {
                $grid->column('source.name', trans('customer.fields.source_option_id'));
                $grid->column('receptionUser.name', trans('customer.fields.reception_user_id'));
                $grid->column('saleUser.name', trans('customer.fields.sale_user_id'));
                $grid->column('name');
                $grid->column('phone');
                $grid->column('wechat');
                $grid->column('chat_images')
                    ->if(function ($column) {
                        return (bool)$column->getValue();
                    })->display(function () {
                        return $this->getChatImages();
                    })->gallery('', 50, 50)
                    ->else()
                    ->display('');
                $grid->column('created_at');

                $_this = $this;
                $grid->filter(function (Grid\Filter $filter) use ($data_permission_is_all) {
                    $filter->like('name');
                    $filter->like('phone');
                    if ($data_permission_is_all) {
                        $filter->like('receptionUser.name', trans('customer.fields.reception_user_id'));
                    }
                    $filter->equal('source.name', trans('customer.fields.source_option_id'))->select(OptionService::getOption(OptionType::SOURCE));
                });

                $grid->actions(function (Grid\Displayers\Actions $actions) use ($_this, $data_permission_is_all) {
                    if (!$actions->row->sale_user_id) {
                        $actions->append(new ReceptionAutoAllocate());
                        $actions->append(new ReceptionAllocate());
                    }
                    if ($data_permission_is_all) {
                        $actions->append(new Delete($_this->type));
                    }
                });

                $grid->enableDialogCreate();
                $grid->disableDeleteButton();
            }

            if ($this->is_sale) {
                //销售部
                $grid->column('source.name', trans('customer.fields.source_option_id'));
                $grid->column('saleUser.name', trans('customer.fields.sale_user_id'));
                $grid->column('returnUser.name', trans('customer.fields.return_user_id'));
                $customer_label_all = CustomerLabel::asSelectArray();
                $customer_label = $customer_label_all;
                unset($customer_label[CustomerLabel::NOT]);
                $grid->column('customer_label')
                    ->if(function ($column) {
                        return $column->getValue() != CustomerLabel::NOT;
                    })
                    ->radio($customer_label, true)
                    ->else()
                    ->radio($customer_label_all, true);
                $grid->column('name');
                $grid->column('phone');
                $grid->column('wechat');
                $grid->column('disease');
                $grid->column('time_of_appointment', trans('customer.fields.register'))->bool();
                $grid->column('deal')->bool();
                $grid->column('sale_remark');
                $grid->column('chat_images')
                    ->if(function ($column) {
                        return (bool)$column->getValue();
                    })->display(function () {
                        return $this->getChatImages();
                    })->gallery('', 50, 50)
                    ->else()
                    ->display('');

                $grid->column('created_at');
                $_this = $this;
                $grid->filter(function (Grid\Filter $filter) use ($data_permission_is_all) {
                    $filter->like('name');
                    $filter->like('phone');
                    if ($data_permission_is_all) {
                        $filter->like('saleUser.name', trans('customer.fields.sale_user_id'));
                    }

                    $filter->equal('source.name', trans('customer.fields.source_option_id'))->select(OptionService::getOption(OptionType::SOURCE));
                });

                //自定义操作

                $grid->actions(function (Grid\Displayers\Actions $actions) use ($_this, $data_permission_is_all) {
                    if ($data_permission_is_all) {
                        $actions->append(new Delete($_this->type));
                    }
                    $actions->append(new Register());
                    if (!$actions->row->salePerformanceFirst) {
                        //添加初诊业绩
                        $actions->append(new SalePerformance());
                    } else {
                        //如果是定金的话
                        if (count($actions->row->salePerformance) < 2 && $actions->row->salePerformanceFirst->type == SalePerformanceType::DEPOSIT) {
                            $actions->append(new Balance());
                        }
                    }
                    //分配
                    if ($actions->row->salePerformanceFirst && !$actions->row->return_user_id) {
                        $actions->append(new AutoAllocate());
                        if ($data_permission_is_all) {
                            $actions->append(new Allocate());
                        }

                    }
                    $actions->append(new Remark($_this->is_sale));
                });


                $grid->enableDialogCreate();
                $grid->disableDeleteButton();

            }
            if ($this->is_return_visit) {
                //复诊部
                $grid->disableCreateButton();
                $grid->disableDeleteButton();

                $grid->column('returnUser.name', trans('customer.fields.return_user_id'));
                $grid->column('saleUser.name', trans('customer.fields.sale_user_id'));
                $grid->column('name');
                $grid->column('phone');
                $grid->column('wechat');
                $grid->column('disease');
                $grid->column('return_remark');
                $grid->column('created_at');

                $grid->filter(function (Grid\Filter $filter) use ($data_permission_is_all) {
                    $filter->like('name');
                    $filter->like('phone');
                    if ($data_permission_is_all) {
                        $filter->like('returnUser.name', trans('customer.fields.return_user_id'));
                    }

                });
                //自定义操作
                $_this = $this;
                $grid->actions(function (Grid\Displayers\Actions $actions) use ($_this, $data_permission_is_all) {
                    if ($data_permission_is_all) {
                        $actions->append(new Delete($_this->type));
                    }
                    $actions->append(new ReturnPerformance());
                    $actions->append(new Remark($_this->is_sale));
                });


            }

        });
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id, new Customer(), function (Show $show) {
            $show->field('id');
            $show->field('source_option_id');
            $show->field('sale_user_id');
            $show->field('name');
            $show->field('phone');
            $show->field('id_card');
            $show->field('wechat');
            $show->field('age');
            $show->field('gender');
            $show->field('province_id');
            $show->field('city_id');
            $show->field('district_id');
            $show->field('address');
            $show->field('doctor_option_id');
            $show->field('disease');
            $show->field('symptom');
            $show->field('time_of_appointment');
            $show->field('treatment_history');
            $show->field('deal');
            $show->field('sale_remark');
            $show->field('consultation');
            $show->field('return_user_id');
            $show->field('return_remark');
            $show->field('created_at');
            $show->field('updated_at');
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form(): Form
    {
        return Form::make(new Customer(), function (Form $form) {

            if ($form->isCreating()) {
                $_this = $this;
                $user_id = $_this::getUserId();
                //新增
                $form->select('source_option_id')->options(OptionService::getOption(OptionType::SOURCE))->required();
                $form->text('disease')->default('');
                $form->text('name', trans('customer.fields.name'))->maxLength(100);
                $form->text('phone', trans('customer.fields.phone'))->maxLength(100)->help(trans('customer.fields.phone') . '/' . trans('customer.fields.wechat') . '/' . trans('customer.fields.name') . '必须填写其中任意一项');
                $form->text('wechat', trans('customer.fields.wechat'))->maxLength(100);
                $form->multipleImage('chat_images', trans('customer.fields.chat_images'))->move( 'images/' . date('Y') . '/' . date('m') . '/' . date('d'))
                    ->uniqueName()
                    ->autoUpload()
                    ->saving(function ($paths) {

                        return count($paths) ?json_encode($paths) : null;
                    });
                $form->hidden('sale_user_id')->default(request('type', ReceptionType::SALE) == ReceptionType::SALE ? $user_id : 0);
                $form->hidden('reception_user_id')->default($user_id);
                $form->hidden('sale_time')->default(request('type', ReceptionType::SALE) == ReceptionType::SALE ? now() : null);
                $form->saving(function (Form $form) use ($_this, $user_id) {

                    $form->name = $form->input('name') ?: '';
                    $form->phone = $form->input('phone') ?: '';
                    $form->wechat = $form->input('wechat') ?: '';
                    $form->disease = $form->input('disease') ?: '';
                    if (!$form->phone && !$form->wechat && !$form->name) {
                        return $form->response()->error(trans('customer.fields.phone') . '/' . trans('customer.fields.wechat') . '/' . trans('customer.fields.name') . '必须填写其中任意一项');
                    }
                    //如果填写了手机号
                    if ($form->phone) {
                        if (!preg_match('/^1[3456789]\d{9}$/', $form->phone)) {
                            return $form->response()->error('请填写正确的手机号码');
                        }
                        //唯一验证
                        if (\App\Models\Customer::query()->where('phone', $form->phone)->exists()) {
                            return $form->response()->error('手机号码已存在');
                        }
                    }
                    //验证微信
                    if ($form->wechat && \App\Models\Customer::query()->where('wechat', $form->wechat)->exists()) {
                        return $form->response()->error('微信已存在');
                    }
                    if (!$user_id) {
                        return $form->response()->error('非员工账号，不可进行此操作');
                    }
                });
            } else {
                $form->text('customer_label');
            }
        });
    }

}
